package com.ada.ielasticsearch;

import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.highlight.HighlightField;

public class SearchApps {

	public static void main(String[] args) throws UnknownHostException, UnsupportedEncodingException {
		// TODO Auto-generated method stub
		/** 检索开始时间 **/

		Pager pager = null;
		/** 获取页面封装好的分页对象 **/
		if (pager == null) {
			pager = new Pager();
			pager.setMaxPageItems(10);
		}

		pager.setDefaultMaxPageItems(1);
		/** 高亮字段 **/
		String[] highFields = new String[] { "content", "title" };

		InetAddress localhost = InetAddress.getByName("localhost");
		// TODO Auto-generated method stub
		// InetSocketTransportAddress
		TransportClient client = TransportClient.builder().build()
				.addTransportAddress(new InetSocketTransportAddress(localhost, 9300));

		
		long startTime = System.currentTimeMillis();

		SearchResponse response = client.prepareSearch("users").setTypes("user").addHighlightedField("name")
				.setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setQuery(QueryBuilders.termQuery("name", "部")) // Query
				// .setFilter(FilterBuilders.rangeFilter("age").from(20).to(30))
				// // Filter
				.setFrom(0).setSize(60).setExplain(true).execute().actionGet();

		/** 总记录数 **/
		long total = response.getHits().totalHits();

		System.out.println("命中总数：" + total);
		SearchHits searchHits = response.getHits();
		SearchHit[] hits = searchHits.getHits();
		for (int i = 0; i < hits.length; i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			SearchHit hit = hits[i];
			String id = hit.getId();

			String name = getHighlightFields(hit, "name");
			System.out.println("***"+name);

			// pageList.add(map);
		}

		/** 检索完成时间 **/
		long endTime = System.currentTimeMillis();
		/** 检索花费时间 **/
		double spendTime = (double) (endTime - startTime) / 1000;
		System.out.println(spendTime);

	}

	/**
	 * 
	 * @Title: getHighlightFields
	 * @Description: 获取带有关键字高亮的内容信息
	 * @param hit
	 *            :记录行
	 * @param field
	 *            :字段
	 * @return String
	 * @author kangj@doone.com.cn
	 * @date 2014-3-18 上午11:17:09
	 */
	public static String getHighlightFields(SearchHit hit, String field) {
		String content = "";
		if (hit != null) {
			Map<String, HighlightField> result = hit.highlightFields();
			HighlightField contentField = result.get(field);
			if (contentField != null) {
				Text[] contentTexts = contentField.fragments();
				for (Text text : contentTexts) {
					content = text.toString();
				}
			} else {
				content = (String) hit.getSource().get(field);
			}
		}
		return content;
	}

}
